﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace WpfApp1.Views;

public partial class TestCavasItems : Window
{
    public TestCavasItems()
    {
        InitializeComponent();
    }

    private async void Add_Click(object sender, RoutedEventArgs e)
    {
        var watch = Stopwatch.StartNew();

        //await Dispatcher.BeginInvoke(AddCanvas, DispatcherPriority.ApplicationIdle);
        var child = new Canvas();
        var ran = new Random();

        Size size = contentHost.RenderSize;
        contentHost.Content = child;

        int x = (int)size.Width;
        int y = (int)size.Height;

        foreach (var item in Enumerable.Range(0, 200_000).Chunk(1_000))
        {
            await Dispatcher.InvokeAsync(() =>
            {
                foreach (var item1 in item)
                {
                    var ele = new Ellipse { Height = 3, Width = 3, Fill = Brushes.Gray };
                    Canvas.SetLeft(ele, ran.Next(x));
                    Canvas.SetTop(ele, ran.Next(y));
                    child.Children.Add(ele);
                }
            }, DispatcherPriority.Background);
        }

        watch.Stop();
        child.Children.Add(new TextBlock { Background = Brushes.White, Text = watch.ElapsedMilliseconds.ToString() });
        Trace.TraceInformation("Add_Click() {0}", watch.ElapsedMilliseconds);
    }

    private void AddCanvas()
    {
        var child = new Canvas();
        var ran = new Random();

        Size size = contentHost.RenderSize;
        int x = (int)size.Width;
        int y = (int)size.Height;

        for (int i = 0; i < 200_000; i++)
        {
            var ele = new Ellipse { Height = 3, Width = 3, Fill = Brushes.Gray };
            Canvas.SetLeft(ele, ran.Next(x));
            Canvas.SetTop(ele, ran.Next(y));
            child.Children.Add(ele);
        }

        contentHost.Content = child;
    }

    private void LoadItems()
    {
    }
}